//
//  NetworkTools.m
//  01-BuDeJie
//
//  Created by beisheng03 on 16/11/3.
//  Copyright © 2016年 xiaomage. All rights reserved.
//

#import "NetworkTools.h"
#import "MJExtension.h"//JSON 对象转换工具 通用
#import "Reachability.h"
@interface NetworkTools ()

@end

@implementation NetworkTools



+ (instancetype)shareNetworkTools
{
    static NetworkTools *instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        // 提示: url的末尾需要有 /
        NSURL *url = [NSURL URLWithString:@"http://mall.xjscvip.com/"];
        NSURLSessionConfiguration *cfg = [NSURLSessionConfiguration defaultSessionConfiguration];
        instance = [[self alloc] initWithBaseURL:url sessionConfiguration:cfg];
        
        instance.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/plain", @"text/javascript",@"text/html" ,nil];
        
        instance.requestSerializer.timeoutInterval = 10;
        
        

        
        [instance setRequestSerializer:[AFHTTPRequestSerializer serializer]];
//        [instance setResponseSerializer:[AFJSONResponseSerializer serializer]];
        
        
//        instance.responseSerializer = [AFXMLParserResponseSerializer serializer];//返回数据为二进制XML数据时用
        
//        instance.responseSerializer  = [AFHTTPResponseSerializer serializer];//返回数据为二进制数据时用
        
//        instance.responseSerializer = [AFJSONResponseSerializer serializer];//返回数据为二进制JSON数据时用
        
//        [instance.requestSerializer setValue:@"iPhone7" forHTTPHeaderField:@"device"];
//        [instance.requestSerializer setValue:@"9.2" forHTTPHeaderField:@"version"];
        
        
    });
    
    return instance;
    
    
}



//普通请求
- (NSURLSessionDataTask *)sendRequestWithHttpMethod:(HTTP_REQUEST_METHOD)method URLPath:(NSString *)pathStr parameters:(id)parameters completionHandler:(completionHandler)completionHandler{
    
    NSError *err = nil;
    id data = nil;
    

    
    if ([[Reachability reachabilityForInternetConnection] currentReachabilityStatus] == NotReachable) {
        

            err = [[NSError alloc] initWithDomain:@"无网络连接..." code:400 userInfo:nil];

        
        
        //主线程执行回调
        dispatch_async(dispatch_get_main_queue(), ^{
            completionHandler(data, err);
        });
        
        return nil;
        
    }



    
    //开始菊花
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    
    
    //初始化请求
    NSString *urlStr = [[NSURL URLWithString:pathStr relativeToURL:self.baseURL] absoluteString];
    
    NSString *methodStr = [self stringWithMethod:method];
    
    NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:methodStr URLString:urlStr parameters:parameters error:nil];
    
    __block NSURLSessionDataTask *task = nil;
    
    
    task = [self dataTaskWithRequest:request uploadProgress:nil downloadProgress:nil completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        
//        NSLog(@"%@",responseObject);
        //结束菊花
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        //判断结果
        NSError *err = nil;
        id data = nil;

        //如果是请求时的错误
        if(error) {
            NSLog(@"%@",error);
           err = [[NSError alloc] initWithDomain:@"请求出错..." code:400 userInfo:nil];
        } else {//请求没有错
            
            if (![responseObject isKindOfClass:[NSDictionary class]]) {
                responseObject = [responseObject mj_keyValues];
            }
            
            NSInteger resultCode = [responseObject[@"code"] integerValue];
            
            if(resultCode == 400) {//400表示失败
                
                
                err = [[NSError alloc] initWithDomain:responseObject[@"error"] code:resultCode userInfo:nil];
                
            } else {
                
                data = responseObject;
                
            }
        }
        //主线程执行回调
        dispatch_async(dispatch_get_main_queue(), ^{
            completionHandler(data, err);
        });
    }];
    
    //发起请求任务
    [task resume];
    return task;
    
    
}



//取消请求
//[self.mgr.tasks makeObjectsPerformSelector:@selector(cancel)];



- (NSString *)stringWithMethod:(HTTP_REQUEST_METHOD)method {
    switch (method) {
        case GET_METHOD:     return @"GET";      break;
        case POST_METHOD:    return @"POST";     break;
        case HEAD_METHOD:    return @"HEAD";     break;
        case PUT_METHOD:     return @"PUT";      break;
        case PATCH_METHOD:   return @"PATCH";    break;
        case DELETE_METHOD:  return @"DELETE";   break;
        default:
            break;
    }
    return @"";
}






@end
